package work.huangxin.share.controller.manhe;

import io.minio.RemoveObjectsArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import work.huangxin.share.constant.RedisConstant;
import work.huangxin.share.domain.manhe.Manhe;
import work.huangxin.share.domain.other.UserMessage;
import work.huangxin.share.domain.other.WXSessionModel;
import work.huangxin.share.mapper.ManheMapper;
import work.huangxin.share.service.ManheService;
import work.huangxin.share.service.OssService;
import work.huangxin.share.service.impl.MinioSysFileServiceImpl;
import work.huangxin.share.service.impl.UserMessageOperationService;
import work.huangxin.share.util.IpUtils;
import work.huangxin.share.util.RedisUtil;
import work.huangxin.share.util.status.BaseResponse;
import work.huangxin.share.util.status.CodeEnum;
import work.huangxin.share.util.status.ResponseData;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * @author: 张锦标
 * @date: 2023/5/12 12:28
 * ManheController类
 */
@RestController
@RequestMapping("/wx/manhe")
public class ManheController {
    @Autowired
    private ManheService manheService;
    @Autowired
    private MinioSysFileServiceImpl minioSysFileService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     *
     * @param sex 字符串0表示要获取的是男生的 字符串1表示要获取女生的
     * @param request
     * @return
     */
    //TODO 让前端限制点击频率？
    @GetMapping("/get/{sex}")
    public BaseResponse get(@PathVariable("sex") String sex, HttpServletRequest request) {
        String remoteHost = IpUtils.getIpAddr(request);
        String key = RedisConstant.MANHE_USERS_GET + remoteHost;
        if (redisUtil.hasKey(key)) {
            int timesByKey = redisUtil.getTimesByKey(key);
            //TODO 若是timesByKey > 3，则可以访问4次，哪个沙比写的？
            if (timesByKey >= 3) {
                return ResponseData.out(CodeEnum.SIGNATURE_NOT_ALLOW, "每个账号每天只能获取3次");
            }
            redisUtil.incr(RedisConstant.MANHE_USERS_GET + remoteHost, 1);
        } else {
            redisUtil.set(RedisConstant.MANHE_USERS_GET + remoteHost, 1);
        }


        List<Manhe> manheList = null;
        Manhe manhe = null;

        if (redisUtil.hasKey(RedisConstant.MANHE_INFO + sex)){
            //得到缓存中 list 集合的 长度
            int cacheSize = (int) redisUtil.lGetListSize(RedisConstant.MANHE_INFO + sex);
            //得到下标,因为[0, cacheSize) -> [1, cacheSize+1) -> [1, cacheSize]
            int index = new Random().nextInt(cacheSize);
            //从缓存中随机拿出数据
            //从list集合的 第 index 个元素拿取数据
            manhe = (Manhe) redisUtil.lGetIndex(RedisConstant.MANHE_INFO + sex, index);

        }else {
            //从数据库中随机获得一条数据，
             manheList = manheService.getManList(sex);
            redisUtil.setCacheList(RedisConstant.MANHE_INFO + sex, manheList);
            //从缓存中随机拿出数据
            //从list集合的 第 index 个元素拿取数据
            int index = new Random().nextInt(manheList.size());
            manhe = (Manhe) redisUtil.lGetIndex(RedisConstant.MANHE_INFO + sex, index);

        }
        return ResponseData.success(manhe);
    }

    @PostMapping("/add")
    public BaseResponse add(@RequestBody Manhe manhe, HttpServletRequest request) {
        String remoteHost = IpUtils.getIpAddr(request);
        String key = RedisConstant.MANHE_USERS_ADD + remoteHost;
        if (redisUtil.hasKey(key)) {
            int timesByKey = redisUtil.getTimesByKey(key);
            //TODO 若是timesByKey > 3，则可以访问4次，哪个沙比写的？
            if (timesByKey >= 3) {
                return ResponseData.out(CodeEnum.SIGNATURE_NOT_ALLOW, "每个账号每天只能新增3次");
            }
            redisUtil.incr(RedisConstant.MANHE_USERS_ADD + remoteHost, 1);
        } else {
            redisUtil.set(RedisConstant.MANHE_USERS_ADD + remoteHost, 1);
        }


        int add = manheService.add(manhe);
        if (add > 0) {
            //若是直接存入redis，id为null，所以直接删除redis中的数据
            redisUtil.del(RedisConstant.MANHE_INFO + manhe.getSex());
            redisUtil.incr(RedisConstant.MANHE_INFO_COUNT, 1);
//            redisUtil.lSet(RedisConstant.MANHE_INFO + manhe.getSex(), manhe);
        }
        return ResponseData.success();
    }

    @PostMapping("/uploadImage")
    public BaseResponse uploadZip(@RequestPart(value = "file",required = false)
                                  MultipartFile file) {
        String ossImageUrl = null;
        try {
            ossImageUrl = minioSysFileService.uploadFileWithZip(file);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ResponseData.success(ossImageUrl);
    }

    @GetMapping("/getAllCount")
    public BaseResponse getAllCount() {
        boolean hasKey = redisUtil.hasKey(RedisConstant.MANHE_INFO_COUNT);

        if (hasKey) {
            int allCount = (int) redisUtil.get(RedisConstant.MANHE_INFO_COUNT);
            return ResponseData.success(allCount);

        } else {
            int count = manheService.getAllCount();
            //24h
            redisUtil.set(RedisConstant.MANHE_INFO_COUNT, count, 60*60*24);
            return ResponseData.success(count);
        }

    }

}
